// pages/utils/wikiapi.js
import config from '../../config.js';

// 缓存键名常量
const CACHE_KEYS = {
  TREE_DATA: 'wiki_tree_data',
  LIST_DATA: 'wiki_list_data',
  LAST_CACHE_TIME: 'wiki_last_cache_time'
};

// 缓存有效期（1小时）
const CACHE_EXPIRY = 60 * 60 * 1000; // 毫秒

// 检查缓存是否有效
const isCacheValid = () => {
  const lastCacheTime = uni.getStorageSync(CACHE_KEYS.LAST_CACHE_TIME);
  if (!lastCacheTime) return false;
  return Date.now() - lastCacheTime < CACHE_EXPIRY;
};

// 保存数据到缓存
const saveToCache = (treeData, listData) => {
  try {
    uni.setStorageSync(CACHE_KEYS.TREE_DATA, treeData);
    uni.setStorageSync(CACHE_KEYS.LIST_DATA, listData);
    uni.setStorageSync(CACHE_KEYS.LAST_CACHE_TIME, Date.now());
  } catch (e) {
    console.error('缓存数据失败:', e);
  }
};

// 从缓存获取数据
const getFromCache = () => {
  try {
    const treeData = uni.getStorageSync(CACHE_KEYS.TREE_DATA);
    const listData = uni.getStorageSync(CACHE_KEYS.LIST_DATA);
    return { treeData, listData };
  } catch (e) {
    console.error('读取缓存失败:', e);
    return { treeData: null, listData: null };
  }
};

// 清除缓存
const clearCache = () => {
  try {
    uni.removeStorageSync(CACHE_KEYS.TREE_DATA);
    uni.removeStorageSync(CACHE_KEYS.LIST_DATA);
    uni.removeStorageSync(CACHE_KEYS.LAST_CACHE_TIME);
  } catch (e) {
    console.error('清除缓存失败:', e);
  }
};

export const fetchWikiData = async () => {
  // 先检查缓存是否有效
  if (isCacheValid()) {
    const cachedData = getFromCache();
    if (cachedData.treeData && cachedData.listData) {
      return cachedData;
    }
  }
  
  // 缓存无效或不存在，从网络获取
  const response = await uni.request({
    url: config.graphqlEndpoint,
    method: 'POST',
    data: {
      query: `
        query {
          pages {
            tree(mode: ALL, locale: "zh") {
              path
              isFolder
              id
              title
            }
            list(orderBy: PATH) {
              id
              title
              path
              description
              updatedAt
              contentType
            }
          }
        }
      `
    },
    header: {
      'content-type': 'application/json',
      'Authorization': `Bearer ${config.authToken}`
    },
  });

  const result = Array.isArray(response) ? response[1].data : response.data;
  if (result?.data) {
    const { tree, list } = result.data.pages;
    
    // 保存到缓存
    saveToCache(tree, list);
    
    return {
      treeData: tree,
      listData: list
    };
  }
  throw new Error('获取数据失败');
};

// 单条内容获取保持不变，不需要缓存
export const fetchSingleContent = async (id) => {
  const response = await uni.request({
    url: config.graphqlEndpoint,
    method: 'POST',
    header: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${config.authToken}`
    },
    data: {
      query: `
        query GetPage($id: Int!) {
          pages {
            single(id: $id) {
              id
              title
              path
              content
              description
              updatedAt
              contentType
            }
          }
        }
      `,
      variables: { id: parseInt(id, 10) }
    }
  });
  
  const result = Array.isArray(response) ? response[1].data : response.data;
  if (result.errors) throw new Error(result.errors[0].message);
  if (!result.data?.pages?.single) throw new Error('未找到页面数据');

  // 预处理 Markdown 内容：修复非标准图片语法
  const rawContent = result.data.pages.single.content;
  const baseUrl = 'https://wiki.xauat.site'; // 你的基础URL
  
  // 定义内容修复函数
  const fixContent = (content) => {
    // 处理非标准Markdown图片语法（![alt](path=600x) → ![alt](path "600px")）
    let fixedContent = content.replace(
      /!\[([^\]]*)\]\(([^)=]+)=(\d+)[xX][)\]]?/g,
      (match, altText, path, width) => {
        return `![${altText}](${encodeURI(path)} "${width}px")`; // 保留尺寸
      }
    );
  
    // 处理HTML <img>标签（修正路径+编码中文）
    fixedContent = fixedContent.replace(
      /<img[^>]+src="([^"]+)"[^>]*>/g,
      (match, src) => {
        const encodedSrc = src.startsWith('http') ? src : baseUrl + encodeURI(src);
        return match.replace(src, encodedSrc);
      }
    );
    
    return fixedContent;
  };

  // 返回处理后的数据
  return {
    ...result.data.pages.single,
    content: fixContent(rawContent) // 调用修复函数处理内容
  };
};